<template>
    <div class="table-compilation-container">
        <!-- 目录面板 -->
        <cardBox class="leftMenu" title="目录" icon="&#xe6f2;">
            <menuAll :CATEGROY="1" :stationId="stationId" @getList="getTableList" menuHeight="calc(100vh - 200px)"
            :showRoleAdd="permissions.showRoleAdd"
            :showRoleDel="permissions.showRoleDel"
            :showRoleEdit="permissions.showRoleEdit"
            />
        </cardBox>

        <!-- 主内容区域 -->
        <div class="main-content">
            <!-- 筛选条件卡片 -->
            <el-card class="filter-card" shadow="hover">
                <div slot="header" class="filter-header">
                    <span class="filter-title">筛选条件</span>
                    <el-button 
                        type="text" 
                        @click="toggleFilterCollapse" 
                        class="collapse-btn"
                    >
                        {{ filterCollapsed ? '展开' : '收起' }}
                        <i :class="filterCollapsed ? 'el-icon-arrow-down' : 'el-icon-arrow-up'"></i>
                    </el-button>
                </div>
                <div v-show="!filterCollapsed" class="filter-content">
                    <el-form :inline="true" size="small" class="filter-form">
                        <el-form-item label="审核状态" class="filter-item">
                            <el-select 
                                v-model="auditStatus" 
                                multiple 
                                placeholder="审核状态" 
                                size="small" 
                                style="width: 200px"
                                @change="handleChangeAuditStatus"
                            >
                                <el-option label="未审核" :value="0"></el-option>
                                <el-option label="审核通过" :value="1"></el-option>
                                <el-option label="审核未通过" :value="2"></el-option>
                            </el-select>
                        </el-form-item>
                        
                        <el-form-item label="模式" class="filter-item">
                            <el-select 
                                v-model="rowState" 
                                placeholder="请选择模式" 
                                @change="handleSetTableMode" 
                                size="small"
                                style="width: 150px"
                            >
                                <el-option label="无模式" :value="0"></el-option>
                                <el-option label="行模式" :value="1"></el-option>
                                <el-option label="列模式" :value="2"></el-option>
                            </el-select>
                        </el-form-item>
                        
                        <el-form-item label="时间类型" class="filter-item">
                            <el-select 
                                v-model="rowTimeState" 
                                placeholder="时间类型" 
                                @change="handleChangeRowTime" 
                                size="small" 
                                style="width: 150px"
                            >
                                <el-option label="截止时间" :value="4"></el-option>
                                <el-option label="时间段" :value="3"></el-option>
                            </el-select>
                        </el-form-item>
                        
                        <el-form-item label="截止时间" class="filter-item" v-if="rowTimeState == 4">
                            <el-date-picker
                                v-model="startTime"
                                type="date"
                                size="small"
                                format="yyyy年MM月dd日"
                                value-format="yyyy/MM/dd"
                                placeholder="请选择日期"
                                style="width: 180px"
                            >
                            </el-date-picker>
                        </el-form-item>     
                        
                        <el-form-item label="时间段" class="filter-item" v-if="rowTimeState == 3">
                            <div class="date-range-picker">
                                <el-date-picker
                                    v-model="startTime"
                                    type="date"
                                    size="small"
                                    format="yyyy年MM月dd日"
                                    value-format="yyyy/MM/dd"
                                    placeholder="开始日期"
                                >
                                </el-date-picker> 
                                <span class="date-separator">至</span>
                                <el-date-picker
                                    v-model="endTime"
                                    type="date"
                                    size="small"
                                    format="yyyy年MM月dd日"
                                    value-format="yyyy/MM/dd"
                                    placeholder="结束日期"
                                >
                                </el-date-picker>
                            </div>
                        </el-form-item>
                        
                        <el-button 
                            type="primary" 
                            size="mini" 
                            @click="handleSetTime" 
                            icon="el-icon-time"
                            class="apply-btn"
                        >
                            确认时间
                        </el-button>
                    </el-form>
                </div>
            </el-card>

            <!-- 表格信息卡片 -->
            <tableCard :tableLoading="tableLoading" :tableHeight="tableHeight" :columns="columns" :tableData="tableData" :showRoleDel="permissions.showRoleDel" :tableRealData="tableRealData" :mergeData="mergeData" :merged="merged"
            @handleDelTable="handleDelTable"  @handleSetCellTable="handleSetCellTable" 
            @refreshTableCell="refreshTableCell"
            @getTableList="getTableList1"/>
        </div>      
    </div>
</template>

<script>
import {getTableByTreeID,setOUTLIERSIGNs,setTableMode,setTableTime,TableDel,setTableCell } from "@/api/https";
import bus from '@/utils/eventBus.js';
import menuAll from '@/components/page/informationAnalysis/menuAll.vue'
import cardBox from "../../components/base/cardBox.vue";
import tableCard from '@/components/page/informationAnalysis/tableCard.vue'
import permissionMixin from '@/utils/permission.js'
export default ({
    name:'tableCompilation',
    components:{menuAll,cardBox,tableCard},
    mixins: [permissionMixin],
    data() {
        return{
            stationId:sessionStorage.getItem("stationId"),
            treeID:'',
            rowState:'',
            tableID:'',
            rowTimeState:'',
            startTime:'',
            endTime:'',
            auditStatus:[],
            filterCollapsed: false,
            tableHeight:'calc(100vh - 420px)',
            columns:[],
            tableData:[],  
            selectedLetters:[],
            tableRealData:[],
            mergeData:[],
            merged:[],
            tableLoading:false,
            resizeHandler: null,
            stationChangedHandler: null
        }
    },
    created(){
        this.initBasin()
        this.calculateTableHeight()
        window.addEventListener('resize', this.calculateTableHeight)
    },
    activated(){
        this.initBasin()
        const newStationId = sessionStorage.getItem("stationId");
        if (this.stationId != newStationId) {
           this.stationId = newStationId;
        }
    },
    deactivated(){
       this.cleanupEventListeners()
    },
    beforeDestroy(){
       this.cleanupEventListeners()
        this.moduleMenuList = [];
        this.menuList = [];
    },
    computed: {
        permissions() {
            return this.getPermissions() || {}
        }
    },
    methods:{
        initBasin() {
            bus.$emit('showBasin', true);
            this.cleanupEventListeners(); 
            this.stationChangedHandler = this.handleStationChanged.bind(this);
            bus.$on('station-changed', this.stationChangedHandler);
        },
        cleanupEventListeners() {
            if (this.stationChangedHandler) {
                bus.$off('station-changed', this.stationChangedHandler);
                this.stationChangedHandler = null;
            }
            if (this.resizeHandler) {
                window.removeEventListener('resize', this.resizeHandler);
                this.resizeHandler = null;
            }
        },
        handleStationChanged(newStationId, targetRoute) {
            if (!targetRoute || targetRoute === this.$route.name) {
                this.stationId = newStationId;
            }
        },
        calculateTableHeight() {
            // 根据窗口大小动态计算表格高度
            const windowHeight = window.innerHeight;
            this.tableHeight = `${windowHeight - 420}px`;
        },
        toggleFilterCollapse() {
            this.filterCollapsed = !this.filterCollapsed;
            if(this.filterCollapsed){
                const windowHeight = window.innerHeight;
                this.tableHeight = `${windowHeight - 350}px`;
            }else{
                this.calculateTableHeight()
            }
        },   
        handleSetTableMode(){
            setTableMode({
                mode:this.rowState,
                tableID:this.tableID
            }).then(res=>{
                if(res.isSuccess){
                    this.$message.success('设置成功！')
                    this.getTableList(this.treeID)
                }else{
                    this.$message.error(res.errorMessage)
                }
            })
        },
        handleChangeRowTime(){
            this.startTime = ''
            this.endTime = ''
        },
        onPushSelectedLetters(list){
            list.forEach(item=>{
                this.selectedLetters.push(item.field)
                if(item.children && item.children.length > 0){
                    this.onPushSelectedLetters(item.children)
                }
            })
        },
        getTableList1(){
            this.getTableList(this.treeID)
        },
        getTableList(treeId){
            if(treeId && treeId == 0){
                this.tableData = []
                this.columns = []
                return
            }
            this.treeID = treeId 
            this.tableLoading = true
            getTableByTreeID({
                TableTreeID:treeId,
                StationID:this.stationId,
                tp:0
            }).then(res=>{
                if(res.isSuccess && res.data && res.data.length > 0){
                    this.selectedLetters = []
                    const _data = res.data[0]
                    this.startTime = _data.b_Time
                    this.endTime = _data.e_Time
                    this.rowState = _data.mode
                    this.rowTimeState = _data.dtModeID
                    this.tableID = _data.id || 0
                    this.auditStatus = _data.outliersigNs || []
                    if(_data.colums && _data.colums.length > 0){
                        this.onPushSelectedLetters(_data.colums)
                        const _d = [..._data.colums]
                        _d.unshift({
                            field: "",
                            key: "rowKey",
                            title: "",
                            width:40,
                            fixed: "left",
                            operationColumn: true,
                            renderBodyCell: ({ row, column, rowIndex }, h) => {
                                return rowIndex + 1;
                            },
                        })
                        this.columns = [..._d]
                        if(_data.tableData == null || _data.tableData.length == 0){
                            this.tableData = [] 
                            this.tableData.push({
                                rowKey:1,
                                text:''
                            })
                        }else{
                            const _list = []
                            _data.tableData.forEach((item,index)=>{
                                const data = {}
                                for(let key in item){
                                    data.rowKey = index + 1
                                    data[key] = item[key].text
                                }
                                _list.push(data)
                            })
                            this.tableData = _list
                            this.tableRealData = _data.tableData
                    }
                    this.mergeData = _data.mergeData || []
                    this.merged = _data.merged || []
                    this.tableLoading = false
                }else{
                    this.columns = []
                    this.tableData = []
                    this.tableLoading = false
                }
                }else{
                    this.tableID = 0
                    this.columns = []
                    this.tableData = []
                    this.tableLoading = false
                }
            })
        },
       
        handleChangeAuditStatus(val){
            setOUTLIERSIGNs({
                tableID:this.tableID,
                OUTLIERSIGNs:val
            }).then(res=>{
                if(res.isSuccess){
                    this.getTableList(this.treeID)
                }else{
                    this.$message.error(res.errorMessage)
                } 
            })
        },
        
        handleSetTime(){
            setTableTime({
                tableID:this.tableID,
                b_Time:this.startTime,
                e_Time:this.endTime,
                DtModeID:this.rowTimeState
            }).then(res=>{
                if(res.isSuccess){
                    this.getTableList(this.treeID)
                }else{
                    this.$message.error(res.errorMessage)
                }
            })
        },
        handleDelTable(){
            this.$confirm(`确认删除该表格，删除后不可恢复，请谨慎操作！是否继续？`,'提示',{
                type:'warning'
            }).then(() => {
                TableDel({
                    ID:this.tableID
                }).then(res=>{
                    if(res.isSuccess){
                        this.columns = []
                        this.tableData = []
                    }
                })
            }).catch(() => {}); 
        },
        
        
        handleSetCellTable(cellData,tableCellText){
            const _data =  {...cellData}
            _data.text = tableCellText
            _data.CODE_ID = cellData.CODE_ID ? cellData.CODE_ID.split(',') : []
            setTableCell(_data).then(res=>{
                if(res.isSuccess && res.data){
                    this.refreshTableCell(res.data)
                }else{
                    const _list = [...this.tableData]
                    const obj1 = _list[_data.row]
                    obj1[_data.TableField] =  cellData.text
                    _list[data.row] = {...obj1} 
                    this.tableData = [..._list]
                    this.$message.error(res.errorMessage)
                }
            })
        },
        refreshTableCell(data){
            // 回填真实表格
            const _listReal = [...this.tableRealData]
            const rowData = _listReal[data.row]
            rowData[data.TableField] = {...data}
            _listReal[data.row] =  {...rowData}
            this.tableRealData = [..._listReal]
        },
        
    }
})
</script>

<style lang="scss" scoped>
.table-compilation-container {
    display: grid;
    grid-template-columns: 340px 1fr;
    height: calc(100vh - 120px);
    .leftMenu{
        width: 340px;
        height: calc(100vh - 120px);
        flex-shrink: 0;
    }
    
    .main-content {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 10px;
        overflow: hidden;
        
        .filter-card, .table-card {
            border-radius: 4px;
            border: none;
            
            ::v-deep .el-card__header {
                padding: 10px;
                border-bottom: 1px solid #ebeef5;
                background-color: #fafbfc;
            }
        }
        
        .filter-card {
            .filter-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding:0 10px;
                
                .filter-title {
                    font-weight: 600;
                    color: #303133;
                }
                
                .collapse-btn {
                    padding: 0;
                    font-size: 13px;
                    color: #409EFF;
                }
            }
            
            .filter-content {
                padding: 20px 4px;
                
                .filter-form {
                    display: flex;
                    flex-wrap: wrap;
                    gap: 10px;
                    
                    .filter-item {
                        margin-bottom: 0;
                    }
                    
                    .date-range-picker {
                        display: flex;
                        align-items: center;
                        
                        .date-separator {
                            margin: 0 8px;
                            color: #909399;
                        }
                    }
                    
                    .apply-btn {
                        margin-left: auto;
                    }
                }
            }
            ::v-deep .el-card__body{
                padding:0 20px;
            }
        }
    }
}
</style>